package com.service.impl;

import com.dao.*;
import com.exception.BusinessException;
import com.exception.LoginTimeOutException;
import com.exception.ServiceRuntimeException;
import com.model.PermissionResource;
import com.model.PermissionRole;
import com.model.SysUser;
import com.po.PermissionRolePO;
import com.service.PermissionRoleService;
import com.utils.BuildTree;
import com.utils.CurrentLoginUserAgent;
import com.utils.SessionUtil;
import com.utils.Tree;
import com.vo.PermissionResourceVO;
import com.vo.PermissionRoleVO;
import com.vo.ResourceVO;
import com.vo.RoleDetailVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
import org.testng.collections.Lists;

import java.util.*;

//去除idea屎黄色：https://blog.csdn.net/dayuang2009/article/details/80393157

/**
 * @Author: chihaojie
 * @Date: 2019/5/31 17:31
 * @Version 1.0
 * @Note
 */

@Service
public class PermissionRoleServiceImpl   implements PermissionRoleService {


    @Autowired
    private PermissionRoleMapper   permissionRoleMapper;

    @Autowired
    private PermissionRoleResourceMapper permissionRoleResourceMapper;


    @Autowired
    private PermissionResourceMapper permissionResourceMapper;

    @Autowired
    private PermissionSysUserRoleMapper permissionSysUserRoleMapper;

    @Autowired
    private SysUserMapper   sysUserMapper;

    @Override
    public PermissionRoleVO add(PermissionRolePO permissionRolePO) {
        Assert.notNull(permissionRolePO,"参数不能为空");
        Long currentUserId = SessionUtil.getCurrentUserId();
        Long businessId = CurrentLoginUserAgent.getBusinessId();
        System.out.println("获取角色列表:  当前用户的id是:   "+currentUserId);
        if(ObjectUtils.isEmpty(currentUserId)){
            throw  new LoginTimeOutException("登录超时,请重新登录");
        }
        SysUser user = sysUserMapper.selectByPrimaryKey(currentUserId);
        PermissionRoleVO result=new  PermissionRoleVO();
        PermissionRole role   =  new PermissionRole();
        Date now  = new Date();
        BeanUtils.copyProperties(permissionRolePO,role);
        role.setAgent(businessId);
        role.setStatus((byte)1);
        //设置时间
        role.setCreated(user.getUserName());
        role.setCreateTime(now);
        permissionRoleMapper.insert(role);
        BeanUtils.copyProperties(role,result);
        //保存角色资源关系
        List<Long>  resourceIds=permissionRolePO.getResourceIds();
        if(!ObjectUtils.isEmpty(resourceIds)){
            Long  roleId     =role.getId();
            if (!ObjectUtils.isEmpty(resourceIds)) {
                // 4.保存选中的角色资源关系
                permissionRoleResourceMapper.insertBatch(resourceIds, roleId);
            }
        }
        retrieveRolesResourceTree(role.getId(), result);
        return result;
    }

    @Override
    public PermissionRoleVO edit(PermissionRolePO permissionRolePO) {
        Assert.notNull(permissionRolePO,"参数不能为空");
        Assert.notNull(permissionRolePO.getId(),"id不能为空");
        PermissionRoleVO result   =  new PermissionRoleVO();
        Date   now = new Date();
        //查询
        PermissionRole role = permissionRoleMapper.selectByPrimaryKey(permissionRolePO.getId());
        if(ObjectUtils.isEmpty(role)){
            throw new ServiceRuntimeException("该记录不存在!");
        }
        if(!ObjectUtils.isEmpty(permissionRolePO.getRoleName())){
            role.setRoleName(permissionRolePO.getRoleName());
        }
        role.setUpdated(permissionRolePO.getUpdated());
        role.setUpdateTime(now);
        permissionRoleMapper.updateByPrimaryKey(role);
        BeanUtils.copyProperties(role,result);
        //保存角色资源关系
        permissionRoleResourceMapper.deleteByRoleId(role.getId());
        List<Long>  resourceIds=permissionRolePO.getResourceIds();
        if(!ObjectUtils.isEmpty(resourceIds)){
            Long  roleId     =role.getId();
            if (!ObjectUtils.isEmpty(resourceIds)) {
                // 4.保存选中的角色资源关系
                permissionRoleResourceMapper.insertBatch(resourceIds, roleId);
            }
        }
        retrieveRolesResourceTree(role.getId(), result);
        return result;
    }

    @Override
    @Transactional
    public Object remove(Long id) {
        Assert.notNull(id,"id不能为空");
        //查询
        PermissionRole role = permissionRoleMapper.selectByPrimaryKey(id);
        if(ObjectUtils.isEmpty(role)){
            throw new ServiceRuntimeException("该记录不存在!");
        }
        if(role.getRoleType().equals(1)){
            throw  new BusinessException(500,"内置角色不允许删除!");
        }

        permissionRoleResourceMapper.deleteByRoleId(id);
        permissionSysUserRoleMapper.deleteByRoleId(id);
        permissionRoleMapper.deleteByPrimaryKey(id);

        return true;
    }

    @Override
    public List<PermissionRoleVO> getRoleList() {
        Long currentUserId = SessionUtil.getCurrentUserId();
        System.out.println("获取角色列表:  当前用户的id是:   "+currentUserId);
        if(ObjectUtils.isEmpty(currentUserId)){
            throw  new LoginTimeOutException("登录超时,请重新登录");
        }
        Long businessId = CurrentLoginUserAgent.getBusinessId();
        List<PermissionRoleVO>   voList= Lists.newArrayList();
        List<PermissionRole> roleList=permissionRoleMapper.selectRoleListByAgent(businessId);
        if(ObjectUtils.isEmpty(roleList)){
         return  voList;
        }else
            for (PermissionRole  role:roleList) {
               //
                PermissionRoleVO  vo=new PermissionRoleVO();
                BeanUtils.copyProperties(role,vo);
                voList.add(vo);
            }
        return voList;
    }

    @Override
    public PermissionRoleVO getRoleInfo(Long id) {
        PermissionRoleVO  vo= new PermissionRoleVO();
        PermissionRole role = permissionRoleMapper.selectByPrimaryKey(id);
        vo.setId(role.getId());
        vo.setRoleName(role.getRoleName());
        retrieveRolesResourceTree(id, vo);
        return vo;
    }

    private void retrieveRolesResourceTree(Long id, PermissionRoleVO vo) {
        List<ResourceVO> resourceVOS=Lists.newArrayList();
        List<Long> roleIdList = Lists.newArrayList();
        roleIdList.add(id);
        //根据角色集合获取资源集合
        //根据角色集合获取资源集合
        List<Long> resourceIdList=  permissionRoleResourceMapper.selectResourceIdList(roleIdList);
        //获取
        //查询所有的资源集合
        for (Long resourceId:resourceIdList) {
            PermissionResource resource = permissionResourceMapper.selectByPrimaryKey(resourceId);
            ResourceVO  voTop=new ResourceVO();
            BeanUtils.copyProperties(resource,voTop);
            voTop.setLevel(resource.getLevel().intValue());
            resourceVOS.add(voTop);
        }
        //创建一个树集合
        List<Tree<ResourceVO>> trees = new ArrayList<Tree<ResourceVO>>(resourceVOS.size());
        //遍历资源集合
        for (ResourceVO  c: resourceVOS) {
            Tree<ResourceVO> tree = new Tree<ResourceVO>(c.getId(), c.getName(), c.getParentId());
            Map<String, Object> attributes = new HashMap<String, Object>();
            attributes.put("level", c.getLevel());
            attributes.put("status", c.getStatus());
            tree.setName(c.getName());
            tree.setComment(c.getComment());
            tree.setParentId(c.getParentId()+"");
            tree.setLevel(String.valueOf(c.getLevel()));
            tree.setLevel(c.getLevel()+"");
            tree.setUrl(c.getUrl());
            tree.setMethod(c.getMethod());
            tree.setAttributes(attributes);
            tree.setChecked(true);
            trees.add(tree);
        }
        List<Tree<ResourceVO>> topNodes = BuildTree.getTopNodes(trees);
        vo.setResourceTree(topNodes);
    }

    @Override
    public RoleDetailVO getRoleDetail(Long id) {
        RoleDetailVO  detailVO=new RoleDetailVO();
        PermissionRole role = permissionRoleMapper.selectByPrimaryKey(id);
        detailVO.setId(role.getId());
        detailVO.setRoleName(role.getRoleName());
        List<Long> roleIdList = Lists.newArrayList();
        roleIdList.add(id);
        //根据角色集合获取资源集合
        List<Long> resourceIdList=  permissionRoleResourceMapper.selectResourceIdList(roleIdList);
        detailVO.setResourceIds(resourceIdList);
        return detailVO;
    }
}
